package com.milloc.db.service.impl;

import com.milloc.db.bo.ScriptBO;
import com.milloc.db.entity.ParameterEntity;
import com.milloc.db.entity.ScriptEntity;
import com.milloc.db.service.ScriptRunnerService;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gongdeming
 * @create 2019-08-27
 */
@Service
@Log4j2
public class ScriptRunnerServiceImpl implements ScriptRunnerService {
    private List<ScriptBO> scripts;

    public ScriptRunnerServiceImpl(ApplicationContext applicationContext) {
        scripts = new ArrayList<>();
        applicationContext.getBeansOfType(ScriptBO.class)
                .forEach((k, v) -> {
                    log.info(String.format("加载脚本service[%s]", k));
                    scripts.add(v);
                });
    }

    @Override
    public Object runScript(ScriptEntity scriptEntity, Map<String, Object> params) {
        for (ScriptBO script : scripts) {
            if (script.supports(scriptEntity)) {
                return script.run(scriptEntity, params);
            }
        }
        throw new IllegalArgumentException("不支持的脚本类型");
    }

    @Override
    public List<ParameterEntity> loadParameter(ScriptEntity scriptEntity) {
        for (ScriptBO script : scripts) {
            if (script.supports(scriptEntity)) {
                return script.loadParameter(scriptEntity);
            }
        }
        throw new IllegalArgumentException("不支持的脚本类型");
    }
}
